//
//  PayTableViewController.m
//  MagazineShangejie
//
//  Created by mac on 15/4/16.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//
//
//
//                      支付订单
//
//
#import "WaitingToPayViewController.h"
#import "PayTableViewController.h"
#import "Util.h"
@interface PayTableViewController (){
    NSMutableArray *_userData;//所有数据
}

@end

@implementation PayTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView=[[UIView alloc]init];
    [SVProgressHUD show];
    self.title=@"支付订单";
    [self loadNews];
    self.tableView.backgroundColor=[UIColor colorWithWhite:0.756 alpha:1.000];

    NSLog(@"_userData ==++ %@",_userData);
    NSLog(@"user ++++++ %@",[UserDefaults objectForKey:@"user"]);
    
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
        //        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        
        //            [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [buttonf setImage:[UIImage imageNamed:@"dismissGray"] forState:UIControlStateNormal];
        
    }
  
    UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;
}


-(void)popOfDismss{
    if ([[self.navigationController viewControllers] count]>=2) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)loadNews{
    [[AppAPIClient sharedClient] GET:@"Payment/Order" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"code"] intValue]==1&&[responseObject[@"data"] count]!=0) {
            _userData=[[NSMutableArray alloc]initWithArray:responseObject[@"data"] copyItems:YES];
            NSLog(@"_userData -+- %@",_userData);
            [self DivideTheDateArray];
            [self.tableView reloadData];
            
        }
        [SVProgressHUD dismiss];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD dismiss];
    }];
}


//区分数据，分别出完成了的和未完成的数据
- (void)DivideTheDateArray{

    for (NSMutableDictionary *payDic in _userData) {
        if ([payDic[@"status"] isEqualToString:@"succ"]) {
//            status.text=[NSString stringWithFormat:@"已支付"];
//            status.textColor = [UIColor lightGrayColor];
        }
        else{
//            status.text=[NSString stringWithFormat:@"未支付"];
//            
//            status.textColor = [UIColor redColor];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _userData.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"paycell" forIndexPath:indexPath];
    if (cell==nil) {
        cell=[tableView dequeueReusableCellWithIdentifier:@"paycell"];
    }
    NSDictionary*dic=_userData[indexPath.row];
    NSLog(@"----dic----%@",dic);
    
    UIImageView*image=(UIImageView*)[cell.contentView viewWithTag:11];
    [image sd_setImageWithURL:[NSURL URLWithString:dic[@"mag"][@"image"]]];
    
    UILabel*name=(UILabel*)[cell.contentView viewWithTag:22];
    name.text=dic[@"mag"][@"catname"];
    
    UILabel*money=(UILabel*)[cell.contentView viewWithTag:33];
    money.text=[NSString stringWithFormat:@"%@.00￥",dic[@"money"]];
    
    UILabel*status=(UILabel*)[cell.contentView viewWithTag:55];
    
    
    if ([dic[@"mag"][@"catname"] isEqualToString:@"铂金Vip购买"] || [dic[@"mag"][@"catname"] isEqualToString:@"钻石Vip购买"]) {
        if ([dic[@"status"] isEqualToString:@"succ"]) {
            status.text=[NSString stringWithFormat:@"已支付"];
            status.textColor = [UIColor lightGrayColor];
        }else{
            
            
            
            //查看订单的状态，如果通过审核就直接跳转支付界面。上传订单号，查看订单状态trial 订单审核状态 0=默认 1=否 2=是
            
            if ([[dic objectForKey:@"trial"] integerValue] == 0) {
                //正在审核
                
                status.text=[NSString stringWithFormat:@"正在审核"];
            }
            
            else if ([[dic objectForKey:@"trial"] integerValue] == 1) {
                //没通过审核
                
                status.text=[NSString stringWithFormat:@"未通过审核"];
            }
            else if ([[dic objectForKey:@"trial"] integerValue] == 2) {
                //通过审核
                
                status.text=[NSString stringWithFormat:@"审核通过"];
            }
            
            status.textColor = [UIColor redColor];
        }

    }
    
    else{
        if ([dic[@"status"] isEqualToString:@"succ"]) {
            status.text=[NSString stringWithFormat:@"已支付"];
            status.textColor = [UIColor lightGrayColor];
        }
        else{
            status.text=[NSString stringWithFormat:@"未支付"];
      
            status.textColor = [UIColor redColor];
            }
    }

//    NSUserDefaults*defaults =[NSUserDefaults standardUserDefaults];
//    NSString*string = [defaults objectForKey:@"AppleLocale"];
//    if([string hasSuffix:@"CN"]){
//        money.text=[NSString stringWithFormat:@"%@%@",money.text,@"￥"];
//    }else if ([string hasSuffix:@"EN"]){
//        money.text=[NSString stringWithFormat:@"%@%@",money.text,@"$"];
//    }else{
//        money.text=[NSString stringWithFormat:@"%@%@",money.text,@"yuan"];
//    }
    
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];

    if ([dic[@"month"] intValue]==1) {
        [adcomps setMonth:+1];
    }else if ([dic[@"month"] intValue]==6){
        [adcomps setMonth:+6];
    }else if ([dic[@"month"] intValue]==12){
        [adcomps setYear:+1];
    }
    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"yyyy-MM-dd"];
    NSDate * dt = [NSDate dateWithTimeIntervalSince1970:[dic[@"addtime"] floatValue]];
    NSDate *toDate = [calendar dateByAddingComponents:adcomps toDate:dt options:0];
    UILabel*date=(UILabel*)[self.view viewWithTag:44];
    date.text=[NSString stringWithFormat:@"%@至%@",[dateformat stringFromDate:dt],[dateformat stringFromDate:toDate]];
    
    
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/




// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
//        Payment/OrderDelete
        [SVProgressHUD show];
        
        
        NSMutableDictionary *deleteDic = [[NSMutableDictionary alloc] init];
        NSLog(@"_userData == %@",_userData);
        deleteDic = _userData [indexPath.row ];
        NSString *trial = [deleteDic objectForKey:@"trial"];
        
        NSNumber *product_type = deleteDic[@"product_type"];
        
        
        
        NSString *catname = [[deleteDic objectForKey:@"mag"] objectForKey:@"catname"];
        NSLog(@"catname --- %@",catname);
        
        NSString *orderName = [[NSString alloc] init];
        NSDictionary *orderDic = [[NSDictionary alloc] init];
        //获取单例的字典
        if([catname rangeOfString:@"铂金"].location !=NSNotFound)//_roaldSearchText
        {
            orderName = @"Goodaaaccc";
            orderDic = [UserDefaults objectForKey:@"Goodaaaccc"];
            NSLog(@"yes");
        }
        
        else
        {
            orderName = @"Diamondaaaccc";
            orderDic = [UserDefaults objectForKey:orderName];
            NSLog(@"no");
        }
        
        if ([product_type integerValue] == 2) {
            //这个是VIP，不是杂志的订阅
            
            if ([trial isEqualToString:@"0"]) {
                [SVProgressHUD showSuccessWithStatus:@"订单正在审核，不能删除。"];
 
                return;
            }
        }
        
        
        
        
        [[AppAPIClient sharedClient] GET:@"Payment/OrderDelete" parameters:@{@"sn":[deleteDic objectForKey:@"trade_sn"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"responseObject------%@",responseObject);
            NSDictionary *trialdata = responseObject[@"data"];
            
            NSLog(@"trialdata == %@",trialdata);
            
            NSNumber *code = responseObject[@"code"];
            
            
            if ([code integerValue] == 1) {
                [_userData removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                //判断有没有本地单例的字典
                if ([orderDic count] > 1) {
                    [UserDefaults removeObjectForKey:orderName];
                }
                [SVProgressHUD dismiss];
            }
            
            else{
            
 
                [SVProgressHUD showSuccessWithStatus:@"删除订单失败，请稍后在试。"];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
 
            [SVProgressHUD showSuccessWithStatus:@"删除订单失败，请稍后在试。"];
        }];

        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}





-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    
    NSMutableDictionary *deleteDic = [[NSMutableDictionary alloc] init];
    NSLog(@"_userData == %@",_userData);
    deleteDic = _userData [indexPath.row ];
    NSString *trial = [deleteDic objectForKey:@"trial"];
    [UserDefaults setObject:trial forKey:@"trial"];
    NSNumber *product_type = deleteDic[@"product_type"];
    
    NSMutableDictionary *orderDic = [[NSMutableDictionary alloc] init];
    [orderDic addEntriesFromDictionary:deleteDic];
    [orderDic addEntriesFromDictionary:[UserDefaults objectForKey:@"user"]];
    NSString *mobile = [[UserDefaults objectForKey:@"user"] objectForKey:@"mobile"];
//    NSString *username = [[UserDefaults objectForKey:@"user"] objectForKey:@"username"];
    [orderDic setObject:mobile forKey:@"telephone"];
//    [orderDic setObject:username forKey:@"username"];
    
    NSString *catname = [[deleteDic objectForKey:@"mag"] objectForKey:@"catname"];
    NSLog(@"catname --- %@",catname);
    
    NSString *orderName = [[NSString alloc] init];
    
    //获取单例的字典
    if([catname rangeOfString:@"铂金"].location !=NSNotFound)//_roaldSearchText
    {
        [UserDefaults setValue:@"VIP" forKey:@"VIP"];
        orderName = @"Goodaaaccc";
//        orderDic = [UserDefaults objectForKey:@"Goodaaaccc"];
        
        [UserDefaults setObject:orderDic forKey:@"Goodaaaccc"];
        NSLog(@"yes");
    }
    
    else
    {
        
        [UserDefaults setValue:@"SVIP" forKey:@"VIP"];
        
        orderName = @"Diamondaaaccc";
//        orderDic = [UserDefaults objectForKey:orderName];
        [UserDefaults setObject:orderDic forKey:@"Diamondaaaccc"];

        NSLog(@"no");
    }
    
    if ([catname rangeOfString:@"Vip"].location !=NSNotFound) {
        //这个是VIP，不是杂志的订阅
        
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        WaitingToPayViewController*web=[story instantiateViewControllerWithIdentifier:@"WaitingToPayViewController"];
        
        [self.navigationController pushViewController:web animated:YES];

        }
    
    
}


//请求接口
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
